package com.topView2;

import com.bean.TreeNode;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * @Author: huangzhigao
 * @Date: 2023/2/12 19:37
 */
public class leecode103 {
    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
        if (root == null) {
            return new ArrayList<>();
        }

        LinkedList<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        List<List<Integer>> res = new ArrayList<>();
        boolean isHead = true;
        while (!queue.isEmpty()) {
            int size = queue.size();
            List<Integer> list = new ArrayList<>();
            if (isHead) {
                //从双端队列的头部弹出,从头弹出，尾部进数，先左后右
                while (size > 0) {
                    TreeNode poll = queue.pollFirst();
                    list.add(poll.val);
                    if (poll.left != null) {
                        queue.addLast(poll.left);
                    }
                    if (poll.right != null) {
                        queue.addLast(poll.right);
                    }
                    size--;
                }
            } else {
                while (size > 0) {
                    TreeNode poll = queue.pollLast();
                    list.add(poll.val);
                    if (poll.right != null) {
                        queue.addFirst(poll.right);
                    }
                    if (poll.left != null) {
                        queue.addFirst(poll.left);
                    }
                    size--;
                }
            }
            isHead = !isHead;
            res.add(list);
        }
        return res;
    }
}
